<?php
namespace catchAdmin\permissions\controller;

use catchAdmin\permissions\excel\orderExport;
use catcher\base\CatchRequest as Request;
use catchAdmin\permissions\model\Permissions;
use catchAdmin\permissions\model\Roles;
use catchAdmin\permissions\model\Users;
use catchAdmin\permissions\request\CreateRequest;
use catchAdmin\permissions\request\UpdateRequest;
use catchAdmin\permissions\request\ProfileRequest;
use catcher\base\CatchController;
use catcher\CatchAuth;
use catcher\CatchCacheKeys;
use catcher\CatchResponse;
use catcher\library\excel\Excel;
use catcher\Tree;
use catcher\Utils;
use think\facade\Cache;

class User extends CatchController
{
    protected $user;

    public function __construct(Users $user)
    {
       $this->user = $user;
    }

    /**
     *
     * @time 2020年04月24日
     * @throws \think\db\exception\DbException
     * @return \think\response\Json
     */
    public function index()
    {
        return CatchResponse::paginate($this->user->getList());
    }
    /**
     *
     * @throws \think\db\exception\DbException
     * @return \think\response\Json
     */
    public function list(CatchAuth $auth,Roles $role,Request $request)
    {
        return CatchResponse::paginate($this->user->getList());

    }
    /**
     *
     * @throws \think\db\exception\DbException
     * @return \think\response\Json
     */
    public function myRoles(CatchAuth $auth,Roles $role)
    {

        $user = $auth->user();
        $roles = $user->getRoles()->toArray();
        //不是超级管理员权限标识 取当前角色和子集角色
        if(is_array($roles)&&$roles[0]['identify'] !== 'admin'){
            $roles = $role->getMyList($roles[0]['id']);

        }else{
            $roles = $role->getList();
        }
        return CatchResponse::success($roles);

    }
    /**
     *
     * @param CreateRequest $request
     * @return \think\response\Json
     */
    public function createUser(CreateRequest $request)
    {

        $params = $request->param();
        if(!empty($params['merchant_name'])){
            $params['merchant_secret'] = $this->get_nonce_str(32);
            $merchant_id = $this->pinyin($params['merchant_name']); //商户号取自公司名称首字母加四个随机数
            $params['merchant_id'] = $merchant_id . rand(1000, 9999); //加上四个随机数
        }
        $id = $this->user->storeBy($params);
        //商户id
        if($params['type'] === 2){
           $this->user->updateBy($id, ['tenant_id'=>$id]); ;//商户的商户id是自己
        }
        $this->user->attachRoles($request->param('roles'));
        return CatchResponse::success('', '新建成功');
    }
    /**
     *
     * @param CreateRequest $request
     * @return \think\response\Json
     */
    public function updateUser(UpdateRequest $request)
    {
        $params = $request->filterEmptyField()->param();
        //生成商户号就不需要接口
        if(empty($params['merchant_id'])&&!empty($params['merchant_name'])){
            $params['merchant_secret'] = $this->get_nonce_str(32);
            $merchant_id = $this->pinyin($params['merchant_name']); //商户号取自公司名称首字母加四个随机数
            $params['merchant_id'] = $merchant_id . rand(1000, 9999); //加上四个随机数
        }
        $params['credit_available_amount'] = $params['credit_amount'];
        $id = $params['id'];
        $this->user->updateBy($id, $params);

        $user = $this->user->findBy($id);
        $user->detachRoles();

        if (!empty($request->param('roles'))) {
            $user->attachRoles($request->param('roles'));
        }
        return CatchResponse::success('', '编辑成功');
    }
    /**
     *
     * @time 2019年12月04日
     * @param $id
     * @return \think\response\Json
     */
    public function delUser(Request $request)
    {
        $id = $request->post('id');
        $ids = Utils::stringToArrayBy($id);

        foreach ($ids as $_id) {
            $user = $this->user->findBy($_id);
            // 删除角色
            $user->detachRoles();
            $this->user->deleteBy($_id);
        }

        return CatchResponse::success('', '删除成功');
    }
    /**
     *
     * @time 2019年12月07日
     * @param $id
     * @return \think\response\Json
     */
    public function switchUser(Request $request)
    {

        $id = $request->post('id');
        $ids = Utils::stringToArrayBy($id);
        foreach ($ids as $_id) {

            $user = $this->user->findBy($_id);

            $this->user->updateBy($_id, [
                'status' => $user->status == Users::ENABLE ? Users::DISABLE : Users::ENABLE,
            ]);
        }
        return CatchResponse::success([], '操作成功');
    }
    /**
     *
     * @throws \think\db\exception\DbException
     * @return \think\response\Json
     */
    public function employeeList(CatchAuth $auth)
    {
        $user = $auth->user();
        return CatchResponse::paginate($this->user->getEmployeeList($user['tenant_id']));
    }
    /**
     *
     * @param CreateRequest $request
     * @return \think\response\Json
     */
    public function createEmployee(CreateRequest $request,CatchAuth $auth)
    {
        $user = $auth->user();
        $params = $request->param();
        $params['type'] = 3; //员工
        $params['tenant_id'] = $user['tenant_id']; //商户id
        $this->user->storeBy($params);
        $this->user->attachRoles($request->param('roles'));
        return CatchResponse::success('', '新建成功');
    }
    /**
     *
     * @param CreateRequest $request
     * @return \think\response\Json
     */
    public function updateEmployee(UpdateRequest $request)
    {
        $params = $request->filterEmptyField()->param();
        $id = $params['id'];
        $this->user->updateBy($id, $params);

        $user = $this->user->findBy($id);
        $user->detachRoles();

        if (!empty($request->param('roles'))) {
            $user->attachRoles($request->param('roles'));
        }
        return CatchResponse::success('', '编辑成功');
    }
    /**
     *
     * @time 2019年12月04日
     * @param $id
     * @return \think\response\Json
     */
    public function delEmployee(Request $request)
    {
        $id = $request->post('id');
        $ids = Utils::stringToArrayBy($id);

        foreach ($ids as $_id) {
            $user = $this->user->findBy($_id);
            // 删除角色
            $user->detachRoles();
            $this->user->deleteBy($_id);
        }

        return CatchResponse::success('', '删除成功');
    }


    /**
     *
     * @time 2019年12月07日
     * @param $id
     * @return \think\response\Json
     */
    public function switchEmployee(Request $request)
    {

        $id = $request->post('id');
        $ids = Utils::stringToArrayBy($id);
        foreach ($ids as $_id) {

            $user = $this->user->findBy($_id);

            $this->user->updateBy($_id, [
                'status' => $user->status == Users::ENABLE ? Users::DISABLE : Users::ENABLE,
            ]);
        }
        return CatchResponse::success([], '操作成功');
    }

    /**
     * 获取用户信息
     *
     * @time 2020年01月07日
     * @param CatchAuth $auth
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @return \think\response\Json
     */
    public function info(CatchAuth $auth)
    {
        $user = $auth->user();
        $roles = $user->getRoles()->column('identify');

        $permissionIds = $user->getPermissionsBy($user->id);
        // 缓存用户权限
        Cache::set(CatchCacheKeys::USER_PERMISSIONS . $user->id, $permissionIds);

        $user->permissions = Permissions::getCurrentUserPermissions($permissionIds);

        $user->roles = $roles;

        // 用户数据权限
        // $user->data_range = Roles::getDepartmentUserIdsBy($roles);

        return CatchResponse::success($user);
    }

    /**
     * 生成随机字符串
     */
    protected function get_nonce_str($length) {
        //字符组合
        $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';

        $len = strlen($str) - 1;

        $randstr = '';

        for ($i = 0; $i < $length; $i++) {

            $num = mt_rand(0, $len);

            $randstr .= $str[$num];

        }

        return $randstr;
    }

    //获取拼音首字母
    public function pinyin($zh) {
        $ret = "";
        $s1 = iconv("UTF-8", "gb2312", $zh);
        $s2 = iconv("gb2312", "UTF-8", $s1);
        if ($s2 == $zh) {
            $zh = $s1;
        }
        for ($i = 0; $i < strlen($zh); $i++) {
            $s1 = substr($zh, $i, 1);
            $p = ord($s1);
            if ($p > 160) {
                $s2 = substr($zh, $i++, 2);
                $ret .= $this->getfirstchar($s2);
            } else {
                $ret .= $s1;
            }
        }
        return $ret;
    }
    //获取首字母
    public function getfirstchar($s0) {
        $fchar = ord($s0[0]);
        if ($fchar >= ord("A") and $fchar <= ord("z")) {
            return strtoupper($s0[0]);
        }

        $s1 = $s0;
        $s2 = $s1;
        //$s1 = iconv("UTF-8","gb2312", $s0);
        //$s2 = iconv("gb2312","UTF-8", $s1);
        if ($s2 == $s0) {$s = $s1;} else { $s = $s0;}
        $asc = ord($s[0]) * 256 + ord($s[1]) - 65536;
        if ($asc >= -20319 and $asc <= -20284) {
            return "a";
        }

        if ($asc >= -20283 and $asc <= -19776) {
            return "b";
        }

        if ($asc >= -19775 and $asc <= -19219) {
            return "c";
        }

        if ($asc >= -19218 and $asc <= -18711) {
            return "d";
        }

        if ($asc >= -18710 and $asc <= -18527) {
            return "e";
        }

        if ($asc >= -18526 and $asc <= -18240) {
            return "f";
        }

        if ($asc >= -18239 and $asc <= -17923) {
            return "g";
        }

        if ($asc >= -17922 and $asc <= -17418) {
            return "h";
        }

        if ($asc >= -17417 and $asc <= -16475) {
            return "j";
        }

        if ($asc >= -16474 and $asc <= -16213) {
            return "k";
        }

        if ($asc >= -16212 and $asc <= -15641) {
            return "l";
        }

        if ($asc >= -15640 and $asc <= -15166) {
            return "m";
        }

        if ($asc >= -15165 and $asc <= -14923) {
            return "n";
        }

        if ($asc >= -14922 and $asc <= -14915) {
            return "o";
        }

        if ($asc >= -14914 and $asc <= -14631) {
            return "p";
        }

        if ($asc >= -14630 and $asc <= -14150) {
            return "q";
        }

        if ($asc >= -14149 and $asc <= -14091) {
            return "r";
        }

        if ($asc >= -14090 and $asc <= -13319) {
            return "s";
        }

        if ($asc >= -13318 and $asc <= -12839) {
            return "t";
        }

        if ($asc >= -12838 and $asc <= -12557) {
            return "w";
        }

        if ($asc >= -12556 and $asc <= -11848) {
            return "x";
        }

        if ($asc >= -11847 and $asc <= -11056) {
            return "y";
        }

        if ($asc >= -11055 and $asc <= -10247) {
            return "z";
        }

        return '';
    }


    /**
     *
     * @param CreateRequest $request
     * @time 2019年12月06日
     * @return \think\response\Json
     */
    public function save(CreateRequest $request)
    {
        $this->user->storeBy($request->param());

        $this->user->attachRoles($request->param('roles'));

        if ($request->param('jobs')) {
            $this->user->attachJobs($request->param('jobs'));
        }

        return CatchResponse::success('', '添加成功');
    }

    /**
     *
     * @time 2019年12月04日
     * @param $id
     * @return \think\response\Json
     */
    public function read($id)
    {
        $user = $this->user->findBy($id);
        $user->roles = $user->getRoles();
        $user->jobs  = $user->getJobs();
        return CatchResponse::success($user);
    }

    /**
     *
     * @time 2019年12月04日
     * @param $id
     * @param UpdateRequest $request
     * @return \think\response\Json
     */
    public function update($id, UpdateRequest $request)
    {
        $this->user->updateBy($id, $request->filterEmptyField()->param());

        $user = $this->user->findBy($id);

        $user->detachRoles();
        $user->detachJobs();

        if (!empty($request->param('roles'))) {
            $user->attachRoles($request->param('roles'));
        }
        if (!empty($request->param('jobs'))) {
            $user->attachJobs($request->param('jobs'));
        }
        return CatchResponse::success();
    }

    /**
     *
     * @time 2019年12月04日
     * @param $id
     * @return \think\response\Json
     */
    public function delete($id)
    {
        $ids = Utils::stringToArrayBy($id);

        foreach ($ids as $_id) {
          $user = $this->user->findBy($_id);
          // 删除角色
          $user->detachRoles();
          // 删除岗位
          $user->detachJobs();

          $this->user->deleteBy($_id);
        }

        return CatchResponse::success();
    }

    /**
     *
     * @time 2019年12月07日
     * @param $id
     * @return \think\response\Json
     */
    public function switchStatus($id): \think\response\Json
    {
        $ids = Utils::stringToArrayBy($id);

        foreach ($ids as $_id) {

          $user = $this->user->findBy($_id);

          $this->user->updateBy($_id, [
            'status' => $user->status == Users::ENABLE ? Users::DISABLE : Users::ENABLE,
          ]);
        }

        return CatchResponse::success([], '操作成功');
    }

    /**
     * 导出
     *
     * @time 2020年09月08日
     * @param Excel $excel
     * @param orderExport $userExport
     * @return \think\response\Json
     *@throws \PhpOffice\PhpSpreadsheet\Exception
     */
    public function export(Excel $excel, orderExport $userExport)
    {
        return CatchResponse::success($excel->save($userExport, Utils::publicPath('export/users')));
    }

    /**
     * 更新个人信息
     *
     * @time 2020年09月20日
     * @param ProfileRequest $request
     * @return \think\response\Json
     */
    public function profile(ProfileRequest $request)
    {
       return CatchResponse::success($this->user->updateBy($request->user()->id, $request->filterEmptyField()->param()));
    }
}
